package network.api;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author mubei
 * @date 2021/12/6
 * @description
 */
public class Work01 {

    @Test()
    public void test1() throws Exception {
        Socket socket = new Socket(InetAddress.getLocalHost(),8888);

        OutputStream outputStream = socket.getOutputStream();

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        bw.write("name");
        bw.flush();
        socket.shutdownOutput();

        InputStream is = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        System.out.println(br.readLine());

        br.close();
        bw.close();
        socket.close();
    }

    @Test()
    public void test2() throws Exception {
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket accept = serverSocket.accept();

        InputStream is = accept.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String s = br.readLine();
        System.out.println(s);
        BufferedWriter bw = null;
        if(s.equals("name")){
            OutputStream outputStream = accept.getOutputStream();
            bw= new BufferedWriter(new OutputStreamWriter(outputStream));
            bw.write("ah");
            // 需要flush 才能写
            bw.flush();
            accept.shutdownOutput();
        }

        br.close();
        bw.close();
        accept.close();
    }
}
